/**
 * Converts an item to HTML . Can not instantiate this class
 * @author zulianp@lu.unisi.ch
 */

package ch.unisi.inf.projects.java.uom.gui;

import java.util.Map;

import ch.unisi.inf.projects.java.uom.Constants;
import ch.unisi.inf.projects.java.uom.Parser;
import ch.unisi.inf.projects.java.uom.elements.Item;
import ch.unisi.inf.projects.java.uom.elements.ItemManager;
import ch.unisi.inf.projects.java.uom.exceptions.UOMException;

public final class ItemHTMLConverter {

	private static final Parser parser = Parser.instance();
	private static final NameController nameController = NameController.instance();
	private static final ItemManager manager= ItemManager.instance();
	private ItemHTMLConverter()
	{}
	
	public static String convertItem(final Item item,final boolean OneStepRecursive)
	{
		String name = item.getField("STRING_NAME");
		String strings = "";
		String items = "";
		String lists = "";
		
		if (item.getField("STRING_NAME") != null)
			strings +="<b>NAME</b>: " + item.getField("STRING_NAME") + "<br>";
		
		for(final Map.Entry<String,String> e : item.getFields().entrySet())
		{
			final String key = e.getKey();
			if(nameController.isEditableField(key)) {
			try {	
					if (key.equals("STRING_NAME"))
						continue;
					String keyType = parser.dbGetVarType(key);
					String keyName = parser.dbGetVarName(key);
					String value = e.getValue();
					
					
					if(Parser.instance().dbColumnTypeIsList(key))
						lists += "<b>" + keyName + "</b>: " + convertList(value) + "<br>";
					else if(keyType.equals(Constants.ITEM_CLASS_STRING.value()))
						strings +="<b>" + keyName + "</b>: " + value + "<br>";
					else
					{
						final Item referencedItem  = manager.itemGet(key,value);
						if(OneStepRecursive)
								strings += convertItem(referencedItem,false);
						else
						{
							String referencedItemName = referencedItem.getField("STRING_NAME");
							if(referencedItemName == null)
								referencedItemName = referencedItem.getName();
							items += "<b>" + keyName + "</b>: " + referencedItemName + "<br>";
						}
					} 
			}
			catch (final UOMException ex1) {
				return null;
			} 
			catch (final Exception ex1) {
				return null;
			}
			}
		}
		return ( "<html>" + "<b>" + name + "</b>" + "<br>" +  strings + items + lists + "</html>");
	}
	
	private static String convertList(final String list)
	{
		int elements = 0;
		if (list != null && !list.equals(""))
			elements = list.split(Constants.ITEM_PARSECHAR.value()).length;
		return "" + elements;
	}
	
}
